package phototagger.imgsim;

import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.zip.GZIPOutputStream;

import javax.imageio.ImageIO;

public class CompressionSimilarityFinder extends SimilarityFinder {
	
  public CompressionSimilarityFinder(File reference) throws IOException {
		super(reference);
  }
	
  public static double imageDistance ( Image i1, Image i2 ) {
	  BufferedImage img1 = toBufferedImage(i1);
	  BufferedImage img2 = toBufferedImage(i2);
	  img1 = rescale(img1);
	  img2 = rescale(img2);	  
	  BufferedImage img3 = new BufferedImage(baseSize * 2, baseSize, BufferedImage.TYPE_INT_RGB);
	  Graphics2D graphics2D = img3.createGraphics();
	  graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
	  graphics2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF);
	  graphics2D.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_SPEED);
	  graphics2D.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_SPEED);	
	  graphics2D.drawImage(img1, 0, 0, baseSize, baseSize, null);
	  graphics2D.drawImage(img2, baseSize, 0, baseSize * 2, baseSize, null);
	  graphics2D.dispose();
	  ByteArrayOutputStream out1 = new ByteArrayOutputStream();
	  ByteArrayOutputStream out2 = new ByteArrayOutputStream();
	  ByteArrayOutputStream out3 = new ByteArrayOutputStream();
	  ByteArrayOutputStream out4 = new ByteArrayOutputStream();
	  GZIPOutputStream out = null;
	  try {
		  out = new GZIPOutputStream(out1);
		  ImageIO.write(img1, "jpg", out);
		  out.close();
		  out = new GZIPOutputStream(out2);
		  ImageIO.write(img2, "jpg", out);
		  out.close();
		  out = new GZIPOutputStream(out3);
		  ImageIO.write(img3, "jpg", out);
		  out.close();
		  out = new GZIPOutputStream(out4);
		  ImageIO.write(img1, "jpg", out);
		  out.flush();
		  ImageIO.write(img2, "jpg", out);
		  out.close();
	  } catch ( Exception ex ) { ex.printStackTrace(); return -1; }
	  double size1 = out1.toByteArray().length;
	  double size2 = out2.toByteArray().length;
	  double size3 = Math.min(out3.toByteArray().length, out4.toByteArray().length);
	  return (size3 - Math.min(size1,size2)) / Math.max( size1, size2 );
  }

}
